<!-- 用户通讯录，前端显示 -->
<template>
  <PageWrapper dense fixedHeight contentClass="flex">
    <!-- 左侧部门树 -->
    <div
      class="ml-0 mr-2 mt-2 w-1/4 xl:w-1/5 overflow-hidden"
      style="border: 1px solid rgb(234, 229, 229)"
    >
      <DeptTree @select="handleSelect" />
    </div>
    <!-- 右侧用户联系信息table -->
    <div
      class="ml-0 mr-0 mt-2 w-3/4 xl:w-4/5 overflow-hidden"
      style="border: 1px solid rgb(234, 229, 229)"
    >
      <!-- <div class="h-auto mb-4 py-2">
        <BasicForm @register="registerForm" @submit="handleSubmit" :showResetButton="false" />
      </div> -->

      <div style="color: rgb(7, 173, 173); font-weight: bold; text-align: center; font-size: large"
        >(按集团用户优惠条件，请尽量使用短号联系)</div
      >
      <BasicTable @register="registerTable" :data-source="dataSource.userCotact" size="small">
        <!-- 定义名称列的筛选功能，搜索内容高亮显示 -->
        <template
          #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        >
          <div style="padding: 8px">
            <a-input
              ref="searchInput"
              :placeholder="`搜索名称`"
              :value="selectedKeys[0]"
              :loading="true"
              style="width: 188px; margin-bottom: 8px; display: block"
              @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
              @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
              type="primary"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <!-- 自定义搜索图标 -->
        <template #customFilterIcon="{ filtered }">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
        </template>
        <!-- 搜索内容过滤高亮 -->
        <template #bodyCell="{ text, column }">
          <span v-if="state.searchText && state.searchedColumn === column.dataIndex">
            <template
              v-for="(fragment, i) in text
                .toString()
                .split(new RegExp(`(?<=${state.searchText})|(?=${state.searchText})`, 'i'))"
            >
              <mark
                v-if="fragment.toLowerCase() === state.searchText.toLowerCase()"
                :key="i"
                class="highlight"
              >
                {{ fragment }}
              </mark>
              <template v-else>{{ fragment }}</template>
            </template>
          </span>
        </template>
      </BasicTable>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, onBeforeMount, onMounted } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  // import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { SearchOutlined } from '@ant-design/icons-vue';

  import { useRouter } from 'vue-router';

  import { query } from '/@/api/addressbook/usercontact/userContact';
  import { conditionFormSchema, userContactTableColumns } from './usercontact/usercontact.data';

  import DeptTree from './usercontact/DeptTree.vue';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'UserContact',
    components: {
      BasicTable,
      PageWrapper,
      // BasicForm,
      DeptTree,
      SearchOutlined,
    },
    setup() {
      //点击部门获取的部门id用于查询部门用户的条件
      const searchInfo = reactive<Recordable>({});

      //用户联系信息数据
      const dataSource = reactive({
        userCotact: [],
      });

      //表单的项目编码和关键字
      const pcode = ref('');
      const words = ref('');

      //筛选输入的内容
      const searchInput = ref();

      const state = reactive({
        searchText: '',
        searchedColumn: '',
      });

      //筛选搜索按钮
      const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        console.log('筛选', selectedKeys);
        state.searchText = selectedKeys[0];
        state.searchedColumn = dataIndex;
      };

      //筛选重置按钮
      const handleReset = (clearFilters) => {
        clearFilters({ confirm: true });
        state.searchText = '';
      };

      const router = useRouter();

      // const [registerForm, { setFieldsValue }] = useForm({
      //   labelWidth: 80,
      //   schemas: conditionFormSchema,
      //   // actionColOptions: {
      //   //   span: 24,
      //   // },
      // });

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable] = useTable({
        // title: '用户联系信息',
        // api: query,
        columns: userContactTableColumns, //表头数据
        // formConfig: {
        //   labelWidth: 80, //设置查询表单中label的宽度
        //   schemas: conditionFormSchema, // form查询表单
        //   showResetButton: false, //查询条件部分中是否显示重置按钮
        // },
        // useSearchForm: false,
        showTableSetting: false, //是否显示表格设置
        showIndexColumn: false,
        canResize: true,
        bordered: true,
        striped: false,
        pagination: false, //关闭分页
        scroll: { y: 400 },
      });

      onBeforeMount(() => {
        //获取路由地址传参 url中的参数使用params获取
        // console.log('当前路由参数：', router.currentRoute.value.params);
        if (router.currentRoute.value.params.project) {
          pcode.value = router.currentRoute.value.params.project;
          // console.log('pcode', pcode.value);
        }
        queryUserContact();
        // getDeptList();
      });
      // onMounted(() => {
      //   //必须要在onMounted中，否则表单还没有加载到前端，无法使用表单中的方法
      //   //设置表单数据
      //   setFieldsValue({
      //     project: pcode.value,
      //   });

      //   queryUserContact();
      // });

      /**
       * 点击部门事件，获取部门id
       * @param dept 部门id
       */
      function handleSelect(dept = '') {
        searchInfo.dept = dept;
        // console.log('选中的部门id', searchInfo.dept);
        queryUserContact();
      }

      /**
       * 表单提交按钮事件
       */
      // function handleSubmit(values: any) {
      //   // console.log('values', values);
      //   pcode.value = values.project;
      //   words.value = values.words;
      //   queryUserContact();
      // }

      /**
       * 查询用户联系信息
       */
      async function queryUserContact() {
        if (dataSource.userCotact.length > 0) {
          dataSource.userCotact = [];
        }
        query({ project: pcode.value, dept: searchInfo.dept, words: words.value })
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              dataSource.userCotact.push(...res);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      return {
        // registerForm,
        registerTable,
        handleSelect,
        searchInfo,
        dataSource,
        // handleSubmit,
        queryUserContact,

        searchInput,
        handleSearch,
        handleReset,
        state,
      };
    },
  });
</script>
<style scoped lang="less">
  .highlight {
    background-color: rgb(250, 216, 170);
    padding: 0px;
  }
  .vben-basic-tree {
    background-color: rgb(248, 239, 232);
  }
</style>
